import message from '@/logic/message';
import callback from '@/logic/callback';
import navigation from '@/logic/navigation';
import axios from 'axios';
import exceptions from './exceptions';

class WeiXin {
    constructor() {

    }
    //跳转页面
    navigateTo(opts){
        const { url ,success} = opts;
        const successId=callback.saveCallback(success);
        message.send({
            type:'trrigerWXApi',
            body:{
                apiName:'navigateTo',
                params:{
                    url,
                    success:successId
                }
            }
        })

    }
    //返回页面
    navigateBack(opts){
        const { url } = opts
        message.send({
            type:'trrigerWXApi',
            body:{
                apiName:'navigateBack',
            }
        })

    }
    //打开小程序
    navigateToMiniProgram(opts){
        const { appId ,path ,success} = opts;
        const successId=callback.saveCallback(success);
        message.send({
            type:'trrigerWXApi',
            body:{
                apiName:'navigateToMiniProgram',
                appId,
                path,
                success:successId
            }
        })

    }
    showToast(opts){
        const { title ,icon ,duration} = opts;
        const { bridgeId } = navigation.getCurrentPageInfo();
        message.send({
            type:'showToast',
            body:{
                bridgeId,
                params:{
                    title,
                    icon,
                    duration,
                }
            }
        })

    }
    //动态设置当前页面的标题
    setNavigationBarTitle(opts){
        const { title ,success} = opts;
        const successId=callback.saveCallback(success);
        message.send({
            type:'trrigerWXApi',
            body:{
                apiName:'setNavigationBarTitle',
                params:{
                    title,
                    success:successId
                }
            }
        })
    }
    //获取窗口信息
    getWindowInfo(){

        /*
            windowWidth	number	可使用窗口宽度，单位px
            windowHeight	number	可使用窗口高度，单位px
            statusBarHeight	number	状态栏的高度，单位px
        */
        /* let result=callback.getWindowInfo();
        // console.log("getWindowInfo:111:",result);

        return {
            windowWidth:result.windowWidth,
            windowHeight:result.windowHeight,
            statusBarHeight:result.statusBarHeight,
        } */

    }

    //==================== start 网络请求 ====================
    /**
     * 发起 HTTPS 网络请求
     * @param {*} opts 
     * timeout 指定请求超时的毫秒数,默认值为 60000
     * @returns 
     */
    request(opts){
        const { url,method='get',data= {},headers= {},responseType='json',timeout="60000",success=()=>{},fail=()=>{},complete=()=>{} }=opts;
        if(!url){
            fail(exceptions.throwError({msg:'请求失败无效的url'}));
            return
        }

		axios({url,method,data,headers,responseType,timeout}).then((res) => {
            let resData={
                status:res.status,
                header:res.headers,
                data:res.data
            };
            success(resData);
            complete(resData);
		}).catch((error)=> {
            let errorData={
                errorCode:error.status,
                message:error.message
            };
            fail(errorData);
            complete(errorData);
		});
    }
    /**
     * 下载文件资源到本地
     * @param {*} opts 
     * timeout 指定请求超时的毫秒数,默认值为 60000
     * @returns 
     */
    downloadFile(opts){
        const { url,headers= {},timeout="60000",success=()=>{},fail=()=>{},complete=()=>{} }=opts;
        if(!url){
            fail({errorCode:1001,message:'请求:失败无效的url'});
            return
        }
		axios({url,method:'post',data,headers,timeout}).then((res) => {
            let resData={
                status:res.status,
                header:res.headers,
                data:res.data
            };
            success(resData);
            complete(resData);
		}).catch((error)=> {
            let errorData={
                errorCode:error.status,
                message:error.message
            };
            fail(errorData);
            complete(errorData);
		});
    }
    /**
     * 将本地资源上传到服务器
     * @param {*} opts 
     * timeout 指定请求超时的毫秒数,默认值为 60000
     * @returns 
     */
    uploadFile(opts){
        const { url,filePath='',name='file',formData={},headers= {},timeout="60000",success=()=>{},fail=()=>{},complete=()=>{} }=opts;
        if(!url){
            fail({errorCode:1001,message:'请求:失败无效的url'});
            return
        }
		// 构造 FormData 对象以发送文件
		const formObj = new FormData();
		formObj.append(name, fileContent, item.fileName);

		axios({url,method:'post',formObj,headers,timeout}).then((res) => {
            let resData={
                status:res.status,
                header:res.headers,
                data:res.data
            };
            success(resData);
            complete(resData);
		}).catch((error)=> {
            let errorData={
                errorCode:error.status,
                message:error.message
            };
            fail(errorData);
            complete(errorData);
		});

    }
    //==================== end 网络请求 ====================


    //==================== start 数据缓存 ====================
    //设置数据缓存
    setStorage(opts){
        const {key,value,success=()=>{},fail=()=>{},complete=()=>{} } = opts;
        if(!key){
            fail(exceptions.throwError({msg:'key不能为空'}));
            return
        }
        message.send({
            type:'trrigerWXApi',
            body:{
                apiName:'setStorage',
                params:{
                    key,
                    value,
                }
            }
        });
        message.receive('setStorage',(res)=>{
            success(res);
            complete(res);
        });
    }
    //获取数据缓存
    getStorage(opts){
        const {key,success=()=>{},fail=()=>{},complete=()=>{} } = opts;
        if(!key){
            fail(exceptions.throwError({msg:'key不能为空'}));
            return
        }
        message.send({
            type:'trrigerWXApi',
            body:{
                apiName:'getStorage',
                params:{
                    key,
                }
            }
        });
        message.receive('getStorage',(res)=>{
            success(exceptions.success({msg:'key不能为空'}));
            complete(res);
        });
    }
    //删除数据
    removeStorage(opts){
        const {key,success=()=>{},fail=()=>{},complete=()=>{} } = opts;
        if(!key){
            fail(exceptions.throwError({msg:'key不能为空'}));
            return
        }
        message.send({
            type:'trrigerWXApi',
            body:{
                apiName:'removeStorage',
                params:{
                    key,
                }
            }
        })
        message.receive('removeStorage',(res)=>{
            success(res);
            complete(res);
        });
    }
    //清除数据缓存
    clearStorage(){
        const {success=()=>{},fail=()=>{},complete=()=>{} } = opts;
        message.send({
            type:'trrigerWXApi',
            body:{
                apiName:'clearStorage',
                params:{
                }
            }
        })
        message.receive('clearStorage',(res)=>{
            success(res);
            complete(res);
        });
    }
    //==================== end 数据缓存 ====================
    //从客户端会话选择文件
    chooseMessageFile(opts){
        const {title=''}=opts || {};
        const ss = navigation.getCurrentPageInfo();
        console.log("bridgeId:",ss)
        /* message.send({
            type:'chooseMessageFile',
            body:{bridgeId}
        }) */
        message.send({
            type:'trrigerWXApi',
            body:{
                apiName:'chooseMessageFile',
                params:{
                    title,
                }
            }
        })
    }
    //设置系统剪贴板的内容
    setClipboardData(opts){
        const { data='',type='text',success=()=>{},fail=()=>{},complete=()=>{} } = opts;
        if(!data){
            fail(exceptions.throwError({msg:'data不能为空'}));
            return
        }
        sendAndReceive({
            body:{
                apiName:'setClipboardData',
                params:{data,type}
            },
            callback:(res)=>{
                success(res);
                complete(res);
            }
        })

    }
    //获取系统剪贴板的内容
    getClipboardData(opts){
        const { data='',type='text',success=()=>{},fail=()=>{},complete=()=>{} } = opts;
        if(!data){
            fail(exceptions.throwError({msg:'data不能为空'}));
            return
        }
        sendAndReceive({
            body:{
                apiName:'getClipboardData',
                params:{data,type}
            },
            callback:(res)=>{
                success(res);
                complete(res);
            }
        })

    }
    //数据变化后DOM更新完成，再执行某些操作。
    nextTick(callback){

        setTimeout(()=> {

            callback || callback();

        }, 2000);

    }
    //打开外部文件
    openExternalFile(callback){
        const { path='',type='exe',success=()=>{},fail=()=>{},complete=()=>{} } = opts;
        if(!path){
            fail(exceptions.throwError({msg:'path不能为空'}));
            return
        }
        sendAndReceive({
            body:{
                apiName:'openExternalFile',
                params:{path,type}
            },
            callback:(res)=>{
                success(res);
                complete(res);
            }
        })

    }

}
export default new WeiXin()